<?php
function C($k=null, $v=null) {
	if(!isset($GLOBALS['CONFIG'])) {
		$GLOBALS['CONFIG'] = include_once(CONF_FILE_PATH);
		foreach($GLOBALS['CONFIG'] as $k=>$v) {
			$GLOBALS['CONFIG']['u____'.$k] = $v;
		}
		$GLOBALS['CONFIG']['u____DBCONFIG'] = $GLOBALS['CONFIG']['db_config'];
		$GLOBALS['CONFIG']['u____WXCONFIG'] = $GLOBALS['CONFIG']['wechat_config'];
	}
	if($k===null) {return $GLOBALS['CONFIG'];}
	if($v===null) {return isset($GLOBALS['CONFIG']['u____' . $k]) ? $GLOBALS['CONFIG']['u____' . $k] : null;}
	$GLOBALS['CONFIG']['u____' . $k] = $v;
	return $v;
}

function config($k=null, $v=null) {
	return C($k, $v);
}

// 跳转
function gourl($url='') {
	if(!$url) return;
	Header("HTTP/1.1 301 Moved Permanently");
	Header("Location: ".$url);
}

function loadView($viewname=null, $tpl="default") {
	if($viewname===null) {$viewname = C('ACTION');}
	$filepath = APP_VIEW_PATH."{$viewname}".APP_VIEW_EXT;
	$headerfile = APP_VIEW_PATH."/tpl/{$tpl}.header".APP_TPL_EXT;
	$footerfile = APP_VIEW_PATH."/tpl/{$tpl}.footer".APP_TPL_EXT;
    if(!file_exists($filepath)) die('view name:: '.$viewname.' Error');
    if(file_exists($headerfile)) include_once($headerfile);
    include($filepath);
    if(file_exists($footerfile)) include_once($footerfile); 
}

function loadAction($actname, $params=array()){
	C('ACTION', $actname);
	if(!empty($params)) {
		C('get', array_merge(C('get'), $params));
	}
	$preActionpath = APP_ROOT."/actions/_begin_load_action.php";
    if(file_exists($preActionpath)) {include($preActionpath);};
    $filepath = APP_ROOT."/actions/page_{$actname}.php";
    if(!file_exists($filepath)) die( $actname . '::Action Error');
    include($filepath);
    $afterActionpath = APP_ROOT."/actions/_after_load_action.php";
    if(file_exists($afterActionpath)) {include($afterActionpath);};
}

function loadWidget($actname, $params=array()) {
	$_action = C('ACTION');
	loadAction($actname, $params);
	C('ACTION', $_action);
}

function message($message='', $targeturl='', $duration=3) {
	loadWidget('message', array('__msg_content'=>$message, '__msg_url'=>$targeturl, '__msg_duration'=>$duration));
	exit;
};

function loadService($serviceName){
	if(C($serviceName)) {return C($serviceName);}
    $filepath = APP_ROOT."/services/{$serviceName}.service.php";
    if(!file_exists($filepath)) die( $serviceName . '::Service Error');
    include($filepath);
    $serviceName = $serviceName .'Service';
   	return C($serviceName, new $serviceName());
}

function loadLib($libname, $type="class") {
	$filepath = APP_ROOT."/lib/{$libname}".($type?".{$type}":"").".php";
    if(!file_exists($filepath)) die( $libname . '::Lib is not exist.');
    include_once($filepath);
}

function loadLibs($libs=array()) {
	foreach($libs as $lib) {
		loadLib(is_array($lib)?$lib['name']:$lib, isset($lib['type'])?$lib['type']:'class');
	}
}

function loadScriptDepends($module) {
	if(is_array($module)) {
		foreach($module as $item) loadScriptDepends($item);
		return;
	}
	if(C('__scriptloaded_'.$module)) return;
	$modules = C('view_files');
	$modulename = $module;
	$module = isset($modules[$module])?$modules[$module]:false;
	if(!$module) return;
	C('__scriptloaded_'.$modulename, 1);

	// TODO 代码可以优化，处理依赖、处理脚本、压缩混淆合并脚本等等
	if(isset($module['import'])) {
		if(!is_array($module['import'])) $module['import']=array($module['import']);
		foreach($module['import'] as $import) loadScriptDepends($import);
	}
	$scripthtml = '';
	if(isset($module['js'])) {
		if(!is_array($module['js'])) $module['js']=array($module['js']);
		foreach($module['js'] as $js) {
			$scripthtml .= '<script src="'.$js.'" _m="'.$modulename.'"></script>';
		};
	}
	if(isset($module['css'])) {
		if(!is_array($module['css'])) $module['css']=array($module['css']);
		foreach($module['css'] as $css) {
			$scripthtml .= '<link rel="stylesheet" href="'.$css.'"  _m="'.$modulename.'"/>';
		};
	}
	echo $scripthtml;
}

// extend funcs
function responseJson($code=0, $message="", $data=array()) {
    if(is_array($code)) {
        $data = $code;
        $code = 0;
    }
    echo json_encode(array(
        'code' => $code,
        'message' => $message,
        'data' => $data?$data:array()
    ));
    exit;
}

function getClientIp($type = 0,$adv=false) {
    $type       =  $type ? 1 : 0;
    static $ip  =   NULL;
    if ($ip !== NULL) return $ip[$type];
    if($adv){
        if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
            $arr    =   explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
            $pos    =   array_search('unknown',$arr);
            if(false !== $pos) unset($arr[$pos]);
            $ip     =   trim($arr[0]);
        }elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
            $ip     =   $_SERVER['HTTP_CLIENT_IP'];
        }elseif (isset($_SERVER['REMOTE_ADDR'])) {
            $ip     =   $_SERVER['REMOTE_ADDR'];
        }
    }elseif (isset($_SERVER['REMOTE_ADDR'])) {
        $ip     =   $_SERVER['REMOTE_ADDR'];
    }
    // IP地址合法验证
    $long = sprintf("%u",ip2long($ip));
    $ip   = $long ? array($ip, $long) : array('0.0.0.0', 0);
    return $ip[$type];
}

/**
 * Cookie 设置、获取、删除
 * @param string $name cookie名称
 * @param mixed $value cookie值
 * @param mixed $option cookie参数
 * @return mixed
 */
function cookie($name='', $value='', $option=null) {
    // 默认设置
    $config = array(
        'prefix'    =>  C('COOKIE_PREFIX'), // cookie 名称前缀
        'expire'    =>  C('COOKIE_EXPIRE'), // cookie 保存时间
        'path'      =>  C('COOKIE_PATH'), // cookie 保存路径
        'domain'    =>  C('COOKIE_DOMAIN'), // cookie 有效域名
        'secure'    =>  C('COOKIE_SECURE'), //  cookie 启用安全传输
        'httponly'  =>  C('COOKIE_HTTPONLY'), // httponly设置
    );
    // 参数设置(会覆盖黙认设置)
    if (!is_null($option)) {
        if (is_numeric($option))
            $option = array('expire' => $option);
        elseif (is_string($option))
            parse_str($option, $option);
        $config     = array_merge($config, array_change_key_case($option));
    }
    if(!empty($config['httponly'])){
        ini_set("session.cookie_httponly", 1);
    }
    // 清除指定前缀的所有cookie
    if (is_null($name)) {
        if (empty($_COOKIE))
            return null;
        // 要删除的cookie前缀，不指定则删除config设置的指定前缀
        $prefix = empty($value) ? $config['prefix'] : $value;
        if (!empty($prefix)) {// 如果前缀为空字符串将不作处理直接返回
            foreach ($_COOKIE as $key => $val) {
                if (0 === stripos($key, $prefix)) {
                    setcookie($key, '', time() - 3600, $config['path'], $config['domain'],$config['secure'],$config['httponly']);
                    unset($_COOKIE[$key]);
                }
            }
        }
        return null;
    }elseif('' === $name){
        // 获取全部的cookie
        return $_COOKIE;
    }
    $name = $config['prefix'] . str_replace('.', '_', $name);
    if ('' === $value) {
        if(isset($_COOKIE[$name])){
            $value =    $_COOKIE[$name];
            if(0===strpos($value,'think:')){
                $value  =   substr($value,6);
                return array_map('urldecode',json_decode(MAGIC_QUOTES_GPC?stripslashes($value):$value,true));
            }else{
                return $value;
            }
        }else{
            return null;
        }
    } else {
        if (is_null($value)) {
            setcookie($name, '', time() - 3600, $config['path'], $config['domain'],$config['secure'],$config['httponly']);
            unset($_COOKIE[$name]); // 删除指定cookie
        } else {
            // 设置cookie
            if(is_array($value)){
                $value  = 'think:'.json_encode(array_map('urlencode',$value));
            }
            $expire = !empty($config['expire']) ? time() + intval($config['expire']) : 0;
            setcookie($name, $value, $expire, $config['path'], $config['domain'],$config['secure'],$config['httponly']);
            $_COOKIE[$name] = $value;
        }
    }
    return null;
}
?>
